package com.gitee.timeddeletion.task;

import com.gitee.timeddeletion.config.TimedDeletionProp;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.stream.Stream;

@Slf4j
@Component
public class DeleteDirTask {

    @Autowired
    private TimedDeletionProp timedDeletionProp;

    @Scheduled(cron = "${timedel.cron}")
    public void deleteDir() {
        log.info("开始删除文件");
        try {
            LocalDateTime nowDate = LocalDateTime.now();
            LocalDateTime endDate = nowDate.minusHours(timedDeletionProp.getRetentionPeriod());
            int endNum = Integer.parseInt(DateTimeFormatter.ofPattern(timedDeletionProp.getDateformat()).format(endDate));
            log.info("删除时间点为{}", endNum);


            if (CollectionUtils.isNotEmpty(timedDeletionProp.getBackupPath())) {
                timedDeletionProp.getBackupPath().forEach(path -> {
                    try {
                        Stream<Path> stream = Files.walk(Paths.get(path), 1);
                        stream.filter(p -> !p.equals(Paths.get(path))).filter(Files::isDirectory).forEach(dir -> {
                            int dirNum = 0;
                            try {
                                dirNum = Integer.parseInt(dir.getFileName().toString());
                            } catch (Exception e) {
                                log.error("文件夹{}名称不是数字", dir.getFileName().toString());
                            }
                            if (0 < dirNum && dirNum <= endNum) {
                                log.info("开始删除文件夹{}", dir);
                                deleteDirectory(dir.toString());
                            } else {
                                log.info("文件夹{}在保留周期内", dir);
                            }
                        });

                    } catch (Exception e) {
                        log.error("遍历文件夹{}异常", path, e);
                    }
                });
            }
        } catch (Exception e) {
            log.error("删除文件异常", e);
        }
    }

    private void deleteDirectory(String path) {
        log.info("开始删除文件夹{}", path);

        try {
            Files.walkFileTree(Paths.get(path), new SimpleFileVisitor<Path>() {

                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    Files.delete(file);
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                    Files.delete(dir);
                    return FileVisitResult.CONTINUE;
                }
            });
        } catch (Exception e) {
            log.error("删除文件夹{}异常", path, e);
        }
    }
}
